<template>
  <el-dialog
    v-model="dialogVisible"
    title="申请权限"
    width="500px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      @submit.prevent="handleSubmit"
    >
      <el-alert
        type="info"
        :closable="false"
        show-icon
        style="margin-bottom: 20px;"
      >
        <template #title>
          您当前缺少访问此功能的权限，可以提交申请等待管理员审批
        </template>
      </el-alert>

      <el-form-item label="目标页面">
        <el-input
          v-model="formData.targetTitle"
          disabled
        />
      </el-form-item>

      <el-form-item label="所需权限">
        <el-tag
          v-for="perm in requiredPermissionsDisplay"
          :key="perm"
          type="warning"
          style="margin-right: 8px; margin-bottom: 8px;"
        >
          {{ perm }}
        </el-tag>
      </el-form-item>

      <el-form-item label="所需角色" v-if="requiredRolesDisplay.length > 0">
        <el-tag
          v-for="role in requiredRolesDisplay"
          :key="role"
          type="danger"
          style="margin-right: 8px; margin-bottom: 8px;"
        >
          {{ role }}
        </el-tag>
      </el-form-item>

      <el-form-item label="申请原因" prop="reason">
        <el-input
          v-model="formData.reason"
          type="textarea"
          :rows="4"
          placeholder="请说明您需要此权限的原因..."
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button
          type="primary"
          :loading="loading"
          @click="handleSubmit"
        >
          提交申请
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useAuthStore } from '../store/auth'
import { usePermissionRequestsStore } from '../store/permissionRequests'

export default {
  name: 'PermissionRequestForm',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    targetRoute: {
      type: String,
      default: ''
    },
    targetTitle: {
      type: String,
      default: ''
    },
    requiredPermissions: {
      type: Array,
      default: () => []
    },
    requiredRoles: {
      type: Array,
      default: () => []
    },
    errorReason: {
      type: String,
      default: 'PERMISSION_DENIED'
    }
  },
  emits: ['update:visible', 'submit', 'cancel'],
  setup(props, { emit }) {
    const authStore = useAuthStore()
    const permissionRequestsStore = usePermissionRequestsStore()
    
    const dialogVisible = ref(props.visible)
    const formRef = ref(null)
    const loading = ref(false)
    
    const formData = ref({
      targetRoute: props.targetRoute,
      targetTitle: props.targetTitle,
      reason: ''
    })
    
    const formRules = {
      reason: [
        { required: true, message: '请说明申请原因', trigger: 'blur' },
        { min: 10, message: '申请原因至少10个字符', trigger: 'blur' }
      ]
    }
    
    // 权限显示名称映射
    const permissionNames = {
      'ticket:read': '查看工单',
      'ticket:create': '创建工单',
      'ticket:update': '更新工单',
      'ticket:delete': '删除工单',
      'ticket:assign': '分配工单',
      'user:manage': '用户管理',
      'system:config': '系统配置',
      'report:view': '查看报表',
      'notification:manage': '通知管理',
      'notification:send': '发送通知',
      'file:upload': '上传文件',
      'file:delete': '删除文件',
      'file:manage': '文件管理'
    }
    
    // 角色显示名称映射
    const roleNames = {
      'admin': '系统管理员',
      'manager': '管理员',
      'agent': '客服',
      'customer': '客户'
    }
    
    const requiredPermissionsDisplay = computed(() => {
      return props.requiredPermissions.map(p => 
        permissionNames[p] || p
      )
    })
    
    const requiredRolesDisplay = computed(() => {
      return props.requiredRoles.map(r => 
        roleNames[r] || r
      )
    })
    
    // 监听visible属性变化
    watch(() => props.visible, (newVal) => {
      dialogVisible.value = newVal
      if (newVal) {
        // 重置表单
        formData.value = {
          targetRoute: props.targetRoute,
          targetTitle: props.targetTitle,
          reason: ''
        }
      }
    })
    
    // 监听dialogVisible变化
    watch(dialogVisible, (newVal) => {
      emit('update:visible', newVal)
    })
    
    const handleSubmit = async () => {
      if (!formRef.value) return
      
      await formRef.value.validate(async (valid) => {
        if (!valid) return
        
        loading.value = true
        
        try {
          const requestData = {
            permission: props.requiredPermissions[0] || null,
            role: props.errorReason === 'ROLE_INSUFFICIENT' ? props.requiredRoles[0] : null,
            reason: formData.value.reason,
            targetResource: props.targetRoute,
            targetTitle: props.targetTitle,
            errorReason: props.errorReason
          }
          
          // 提交到store
          await permissionRequestsStore.submitRequest(requestData)
          
          // 同时保存到authStore
          authStore.addPermissionRequest(requestData)
          
          ElMessage.success('权限申请已提交，请等待管理员审批')
          
          emit('submit', requestData)
          dialogVisible.value = false
        } catch (error) {
          ElMessage.error('提交申请失败：' + error.message)
        } finally {
          loading.value = false
        }
      })
    }
    
    const handleCancel = () => {
      emit('cancel')
      dialogVisible.value = false
    }
    
    const handleClose = () => {
      emit('update:visible', false)
    }
    
    return {
      dialogVisible,
      formRef,
      loading,
      formData,
      formRules,
      requiredPermissionsDisplay,
      requiredRolesDisplay,
      handleSubmit,
      handleCancel,
      handleClose
    }
  }
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>

